import time

from selenium.webdriver.common.by import By

from base.MerchantXpath import MerchantBase
from base.ObjectMap import ObjectMap


class MerchantPage(MerchantBase, ObjectMap):
    def common_click_button(self, driver, button_name):
        button_xpath = self.common_button(button_name)
        return self.element_click(driver, By.XPATH, button_xpath)

    def common_input_value(self, driver, label_name, input_value):
        input_xpath = self.label_input(label_name)
        return self.element_fill_value(driver, By.XPATH, input_xpath, input_value)

    def click_active_button(self, driver, button_name):
        button_xpath = self.active_button(button_name)
        return self.element_click(driver, By.XPATH, button_xpath)

    def uncheck(self, driver, target):
        hidden_xpath = self.hidden_checkbox(target)
        if self.element_get(driver, By.XPATH, hidden_xpath).is_selected():
            displayed_xpath = self.displayed_checkbox(target)
            self.element_click(driver, By.XPATH, displayed_xpath)

    def check(self, driver, target):
        hidden_xpath = self.hidden_checkbox(target)
        if not self.element_get(driver, By.XPATH, hidden_xpath).is_selected():
            displayed_xpath = self.displayed_checkbox(target)
            self.element_click(driver, By.XPATH, displayed_xpath)

    def does_direct_merchant_exist(self, driver, merchant_name, enterprise_name):
        self.uncheck(driver, "includeSubEnterprise")
        self.common_click_button(driver, "Filter")
        self.common_input_value(driver, "Name", merchant_name)
        self.common_click_button(driver, "Search")
        name_xpath = self.merchant_name(merchant_name, enterprise_name)
        return self.element_is_display(driver, By.XPATH, name_xpath)

    def create_merchant(self, driver, merchant_name, enterprise_name):
        if self.does_direct_merchant_exist(driver, merchant_name, enterprise_name):
            return True
        self.common_click_button(driver, "Create")
        self.common_input_value(driver, "Name", merchant_name)
        self.click_active_button(driver, "Next")
        self.check(driver, "InheritEnterpriseExpiryDate")
        self.click_active_button(driver, "Create")
        time.sleep(1)
        self.click_active_button(driver, "Next")
        time.sleep(1)
        self.click_active_button(driver, "Save")
        return True
